/* $RCSFile: FileExplorerTextBox.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/FileExplorerTextBox.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Resources;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{

    public class FileExplorerTextBox : CompositeControl
    {
        RadWindow rdwnd                 =   null;
        WebControl inputTb              =   null;
        Button BrowseBtn                =   null;
        
        Unit _WindowWidth               =   new Unit("530px");
        Unit _WindowHeight              =   new Unit("550px");

        UploadFileType _FileType        =   UploadFileType.Image;
        string Btn_Value                =   " ... ";
        string Btn_Text                 =   string.Empty;
        string Btn_UploadDirectory      =   string.Empty;
        int Btn_MaxWidth                =   -1;
        int Btn_MaxHeight               =   -1;
        int Btn_TotalWidth              =   -1;
        int Btn_TotalHeight             =   -1;
        int Btn_MinWidth                =   -1;
        int Btn_MinHeight               =   -1;
        int Btn_MaxBytes                =   -1;
        string Btn_FileTypes            =   string.Empty;
        bool Btn_AllowUpload            =   true;
        bool Btn_AllowDelete            =   false;
        bool Btn_AllowEdit              =   true;
        bool Btn_AllowCreateDirectory   =   true;
        bool Btn_AllowEditTextBox       =   false;
        bool Btn_AllowRename            =   false;

        public FileExplorerTextBox()
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox Ctor Called.",WebControlsTraceSwitch.Sw.Info);
        }

        public FileExplorerTextBox(UploadFileType FType)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox Ctor BEG FileType: {0}.",FType),WebControlsTraceSwitch.Sw.Info);
            FileType    =   FType;
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox Ctor END.",WebControlsTraceSwitch.Sw.Info);
        }


        public Unit WindowWidth
        {
            get
            {
                return _WindowWidth;
            }
            set
            {
                 _WindowWidth  =   value;

            }
        }
        
        public Unit WindowHeight
        {
            get
            {
                return _WindowHeight;
            }
            set
            {
                 _WindowHeight  =   value;

            }
        }

        [DefaultValue("Image"), Description("Get/Set Default file type."), Bindable(true), Category("Data")]
        public UploadFileType FileType
        {
            get
            {
                return _FileType;
            }
            set
            {
                 _FileType  =   value;

            }
        }


        // Properties
        [DefaultValue("false"), Description("Gets/sets the AllowCreateDirectory."), Bindable(true), Category("Data")]
        public bool AllowCreateDirectory
        {
            get
            {
                return Btn_AllowCreateDirectory;
            }
            set
            {
                Btn_AllowCreateDirectory = value;
            }
        }

        [Description("Gets/sets the AllowDelete."), DefaultValue("false"), Bindable(true), Category("Data")]
        public bool AllowDelete
        {
            get
            {
                return Btn_AllowDelete;
            }
            set
            {
                Btn_AllowDelete = value;
            }
        }

        [Category("Data"), Description("Gets/sets the AllowEdit."), Bindable(true), DefaultValue("false")]
        public bool AllowEdit
        {
            get
            {
                return Btn_AllowEdit;
            }
            set
            {
                Btn_AllowEdit = value;
            }
        }

        [Description("Gets/sets the AllowEditTextBox.")]
        public bool AllowEditTextBox
        {
            get
            {
                return Btn_AllowEditTextBox;
            }
            set
            {
                Btn_AllowEditTextBox = value;
            }
        }

        [Description("Gets/sets the AllowRename.")]
        public bool AllowRename
        {
            get
            {
                return Btn_AllowRename;
            }
            set
            {
                Btn_AllowRename = value;
            }
        }

        [Description("Gets/sets the AllowUpload."), Bindable(true), Category("Data"), DefaultValue("true")]
        public bool AllowUpload
        {
            get
            {
                return Btn_AllowUpload;
            }
            set
            {
                Btn_AllowUpload = value;
            }
        }


        [Description("Gets/sets the Text.")]
        public string Text
        {
            get
            {
                if ( ChildControlsCreated && Controls.Count > 2)
                {
                    if (Config.UseRadControlsForSettings)
                        return ((RadTextBox)Controls[0]).Text;
                    return ((TextBox)Controls[0]).Text;
                }
                return Btn_Text;
            }
            set
            {
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox Text SET value: {0}, Controls.Count: {1}.",
                        value,Controls.Count),WebControlsTraceSwitch.Sw.Info);
                Btn_Text                                =   value;
                if (ChildControlsCreated && Controls.Count > 2)
                {
                    if (Config.UseRadControlsForSettings)
                        ((RadTextBox)Controls[0]).Text  =   value;
                    else ((TextBox)Controls[0]).Text    =   value;
                }
            }
        }


        [Description("Sets the FileTypes."), Bindable(true), Category("Data"), DefaultValue("jpg,gif,png")]
        public string FileTypes
        {
            get
            {
                if ( string.IsNullOrEmpty(Btn_FileTypes) )
                    switch (FileType)
                    {
                        default:
                            Btn_FileTypes   =   "*.*";
                        break;
                        case UploadFileType.Image:
                            Btn_FileTypes   =   "*.jpg,*.gif,*.png";
                            break;
                        case UploadFileType.Media:
                            Btn_FileTypes   =   "*.wmv,*.wma,*.*";
                            break;
                        case UploadFileType.Flash:
                            Btn_FileTypes   =   "*.swf,*.*";
                            break;
                        case UploadFileType.SilverLight:
                            Btn_FileTypes   =   "*.xap,*.*";
                            break;
                        case UploadFileType.Document:
                            Btn_FileTypes   =   "*.*";
                            break;
                        case UploadFileType.Template:
                            Btn_FileTypes   =   "*.*";
                            break;
                     }
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox FileTypes GET value: {0}.",Btn_FileTypes),WebControlsTraceSwitch.Sw.Info);
                return Btn_FileTypes;
            }
            set
            {
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox FileTypes SET value: {0}.",value),WebControlsTraceSwitch.Sw.Info);
                Btn_FileTypes               =   value;
            }
        }

        [Description("Gets/sets the MaxBytes."), Category("Data"), DefaultValue("-1"), Bindable(true)]
        public int MaxBytes
        {
            get
            {
                return Btn_MaxBytes;
            }
            set
            {
                Btn_MaxBytes = value;
            }
        }

        [Description("Gets/sets the MaxHeight."), Bindable(true), Category("Data"), DefaultValue("-1")]
        public int MaxHeight
        {
            get
            {
                return Btn_MaxHeight;
            }
            set
            {
                Btn_MaxHeight = value;
            }
        }

        [Bindable(true), Description("Gets/sets the MaxWidth."), Category("Data"), DefaultValue("-1")]
        public int MaxWidth
        {
            get
            {
                return Btn_MaxWidth;
            }
            set
            {
                Btn_MaxWidth = value;
            }
        }

        [Category("Data"), Description("Gets/sets the MinHeight."), DefaultValue("-1"), Bindable(true)]
        public int MinHeight
        {
            get
            {
                return Btn_MinHeight;
            }
            set
            {
                Btn_MinHeight = value;
            }
        }

        [Bindable(true), Category("Data"), Description("Gets/sets the MinWidth."), DefaultValue("-1")]
        public int MinWidth
        {
            get
            {
                return Btn_MinWidth;
            }
            set
            {
                Btn_MinWidth = value;
            }
        }

        [Bindable(true), DefaultValue("-1"), Description("Gets/sets the TotalHeight."), Category("Data")]
        public int TotalHeight
        {
            get
            {
                return Btn_TotalHeight;
            }
            set
            {
                Btn_TotalHeight = value;
                Btn_MinHeight = value;
                Btn_MaxHeight = value;
            }
        }

        [DefaultValue("-1"), Description("Gets/sets the TotalWidth."), Category("Data"), Bindable(true)]
        public int TotalWidth
        {
            get
            {
                return Btn_TotalWidth;
            }
            set
            {
                Btn_TotalWidth = value;
                Btn_MinWidth = value;
                Btn_MaxWidth = value;
            }
        }
        
        /// <summary>
        /// The upload directory defaults to PortalSettings.DefaultImageVirtualPath
        /// </summary>
        [Category("Data"), DefaultValue("images/"), Description("Gets/sets the UploadDirectory."), Bindable(true)]
        public string UploadDirectory
        {
            get
            {
                if ( string.IsNullOrEmpty(Btn_UploadDirectory) &&
                     HttpContext.Current != null  )
                {
                        if (HttpContext.Current.Items[StStr.strPortalSettings] != null)
                        {
                            PortalSettings portalSettings   =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                            switch (FileType)
                            {
                                default:
                                case UploadFileType.Image:
                                    Btn_UploadDirectory     =   portalSettings.DefaultImageVirtualPath;
                                    break;
                                case UploadFileType.Media:
                                    FileTypes               =   "*.wmv,*.wma,*.*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultMediaVirtualPath;
                                    break;
                                case UploadFileType.Flash:
                                    FileTypes               =   "*.swf,*.*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultFlashVirtualPath;
                                    break;
                                case UploadFileType.SilverLight:
                                    FileTypes               =   "*.xap,*.*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultSilverlightVirtualPath;
                                    break;
                                case UploadFileType.Document:
                                    FileTypes               =   "*.*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultDocumentVirtualPath;
                                    break;
                                case UploadFileType.Template:
                                    FileTypes               =   "*.*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultTemplateVirtualPath;
                                    break;
                             }
                        }
                }
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox UploadDirectory GET FileType: {0}, Btn_UploadDirectory: {1}.",FileType,Btn_UploadDirectory),WebControlsTraceSwitch.Sw.Info);
                return Btn_UploadDirectory;
            }
            set
            {
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox UploadDirectory SET BEG value: [{0}]",value),WebControlsTraceSwitch.Sw.Info);
                if ( string.IsNullOrEmpty(value) && HttpContext.Current != null  )
                {
                        if (HttpContext.Current.Items[StStr.strPortalSettings] != null)
                        {
                            PortalSettings portalSettings   =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                            switch (FileType)
                            {
                                default:
                                case UploadFileType.Image:
                                    Btn_UploadDirectory     =   portalSettings.DefaultImageVirtualPath;
                                    break;
                                case UploadFileType.Media:
                                    FileTypes               =   "wmv,wma,*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultMediaVirtualPath;
                                    break;
                                case UploadFileType.Flash:
                                    FileTypes               =   "swf,*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultFlashVirtualPath;
                                    break;
                                case UploadFileType.SilverLight:
                                    FileTypes               =   "xap,*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultSilverlightVirtualPath;
                                    break;
                                case UploadFileType.Document:
                                    FileTypes               =   "*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultDocumentVirtualPath;
                                    break;
                                case UploadFileType.Template:
                                    FileTypes               =   "*";
                                    Btn_UploadDirectory     =   portalSettings.DefaultTemplateVirtualPath;
                                    break;
                             }
                        }
                }
                else
                {
                    Btn_UploadDirectory                     =   value;
                }
                if ( Btn_UploadDirectory != string.Empty && !Btn_UploadDirectory.EndsWith("/"))
                    Btn_UploadDirectory                     +=  "/";
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox UploadDirectory SET val: {0}", Btn_UploadDirectory),WebControlsTraceSwitch.Sw.Info);
            }
        }

        [Description("Gets/sets the Value."), Bindable(true), Category("Appearance"), DefaultValue(" ... ")]
        public string Value
        {
            get
            {
                return Btn_Value;
            }
            set
            {
                Btn_Value = value;
            }
        }

        /// <summary>
        /// This member overrides Control.CreateChildControls
        /// </summary>
        protected override void CreateChildControls()
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox CreateChildControls BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
            CreateControlHierarchy();
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox CreateChildControls END ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox OnPreRender BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
            base.OnPreRender(e);
            EnsureChildControls();
            PrepareControlHierarchy();
            // Insert scripts
            StringBuilder sb        =   new StringBuilder();
            sb.AppendFormat("function OpenFileExplorerDialog_{0}(){{\nvar wnd = $find('{1}');\nwnd.show();\n}}\n",ClientID,rdwnd.ClientID);
            string script       =   sb.ToString();
            ((ADNPage)Page).RegisterADNClientScriptBlock(GetType(),"OpenFileExplorer"+ClientID,script,true);
            BrowseBtn.OnClientClick =   string.Format("OpenFileExplorerDialog_{0}(); return false;",ClientID);
            //This function is called from the Explorer.aspx page
            script       =   "function OnFileSelected(wnd, fileSelected,tbId){\nvar textbox = $find(tbId);\nif(textbox.set_value) textbox.set_value(fileSelected); else textbox.value= fileSelected;\n}\n";
            ((ADNPage)Page).RegisterADNClientScriptBlock(GetType(),"FileExplorer",script,true);

            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox OnPreRender END.",WebControlsTraceSwitch.Sw.Info);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox Render BEG.",WebControlsTraceSwitch.Sw.Info);
            if ( DesignMode )
                EnsureChildControls();
            try
            {
                base.Render(writer);
            }
            catch(Exception ex)
            { 
                if ( WebControlsTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FileExplorerTextBox Render ex: {0}", ex),WebControlsTraceSwitch.Sw.Info);
                throw;
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox Render END.",WebControlsTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Apply styles during render phase, so the user can change styles
        /// after calling DataBind without the property changes ending
        /// up in view state.
        /// </summary>
        private void PrepareControlHierarchy()
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox PrepareControlHierarchy BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
            EnsureChildControls();
            if (Config.UseRadControlsForSettings)
            {
                RadTextBox rtb          =   (RadTextBox)inputTb;
                rtb.Text                =   Btn_Text;
                if ( !Width.IsEmpty )
                    rtb.Width           =   new Unit(3*Width.Value/4,Width.Type);
            }
            else
            {
                TextBox ntb             =   (TextBox)inputTb;
                ntb.Text                =   Btn_Text;
                if ( !Width.IsEmpty )
                    ntb.Width           =   new Unit(3*Width.Value/4,Width.Type);
            }
            // Set the navigateurl of radwindow in order it transmit the inputTbId
            string NavUrl           =   string.Format("{0}RadExplorer.aspx?ViewPath={1}&searchPat={2}&senderTbId={3}",
                new object[]{Config.PortalFileExplorerPath,HttpUtility.HtmlEncode(UploadDirectory),HttpUtility.HtmlEncode(FileTypes),HttpUtility.HtmlEncode(inputTb.ClientID)});
            if ( !string.IsNullOrEmpty(Btn_Text) )
            {
                string pth          =   UploadDirectory;
                if ( !pth.EndsWith("/") )
                    pth             +=  "/";
                string sel          =   string.Format("{0}{1}",pth,Btn_Text);
                NavUrl              +=  string.Format("&Sel={0}",Page.Server.HtmlEncode(sel));
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox PrepareControlHierarchy NavigateUrl: '{0}'.",NavUrl),WebControlsTraceSwitch.Sw.Info);
            rdwnd.NavigateUrl       =   NavUrl;
            //Button Btn                  =   (Button)Controls[1];
            if ( BrowseBtn != null )
            {
                //Btn.Text                =   Btn_Value;
                /*
                Btn.MaxWidth            =   Btn_MaxWidth;
                Btn.MaxHeight           =   Btn_MaxHeight;
                Btn.TotalWidth          =   Btn_TotalWidth;
                Btn.TotalHeight         =   Btn_TotalHeight;
                Btn.MinWidth            =   Btn_MinWidth;
                Btn.MinHeight           =   Btn_MinHeight;
                Btn.MaxBytes            =   Btn_MaxBytes;
                Btn.AllowUpload         =   Btn_AllowUpload;
                Btn.AllowDelete         =   Btn_AllowDelete;
                Btn.AllowEdit           =   Btn_AllowEdit;
                Btn.AllowCreateDirectory = Btn_AllowCreateDirectory;
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox PrepareControlHierarchy FileType: {0}, FileTypes: {1}.",
                        FileType,FileTypes),WebControlsTraceSwitch.Sw.Info);
                 * */
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox PrepareControlHierarchy END.",WebControlsTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// This member overrides Control.CreateControlHierarchy
        /// </summary>
        private void CreateControlHierarchy()
        {
            // NEVER hide controls on this routine
            // some events WILL NOT FIRED
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox CreateControlHierarchy BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
            try
            {
                ClearChildViewState();
                Controls.Clear();
                if ( Config.UseRadControlsForSettings )
                {
                    RadTextBox rtb      =   new RadTextBox();
                    rtb.TextMode        =   InputMode.SingleLine;
                    inputTb             =   rtb;
                }
                else
                {
                    TextBox ntb         =   new TextBox();
                    ntb.TextMode        =   TextBoxMode.SingleLine;
                    inputTb             =   ntb;
                }

                inputTb.ID              =   "src";
                Controls.Add(inputTb);

                BrowseBtn               =   new Button();
                BrowseBtn.ID            =   "upl";
                Controls.Add(BrowseBtn);
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox CreateControlHierarchy BEG Btn.ClientID: {0}", BrowseBtn.ClientID),WebControlsTraceSwitch.Sw.Info);


                rdwnd                   =   new RadWindow();
                rdwnd.ID                =   "ExplorerWindow";
                rdwnd.Width             =   WindowWidth;
                rdwnd.Height            =   WindowHeight;
                rdwnd.VisibleStatusbar  =   false;
                if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FileExplorerTextBox CreateControlHierarchy BEG WindowWidth: {0}, WindowHeight: {1}", 
                        WindowWidth,WindowHeight),WebControlsTraceSwitch.Sw.Info);
                rdwnd.Modal             =   true;
                rdwnd.Behaviors         =   WindowBehaviors.Move | WindowBehaviors.Close;
                Controls.Add(rdwnd);
                ChildControlsCreated    =   true;
            }
            catch ( Exception ex )
            {
                if ( WebControlsTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]FileExplorerTextBox CreateControlHierarchy ex: {0}.",ex),WebControlsTraceSwitch.Sw.Info);
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FileExplorerTextBox CreateControlHierarchy END.",WebControlsTraceSwitch.Sw.Info);
        }
    }
}

